package www.com.library.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import www.com.common.library.R;
import www.com.library.app.Logger;
import www.com.library.util.ProductPrecision;
import www.com.library.util.DoubleConverter;

/**
 * 价格输入框基础类
 *
 */
public class NumberInput extends EditText {

	/**
	 * 文本修改响应接口
	 * @author Administrator
	 *
	 */
	public interface OnTextChangedListener {
		void onTextChanged(EditText edit, Editable s);
	}

	public static final int MAX_NUM_OF_INTEGERS = 7;
	private int mMaxDigitBeforeDot = MAX_NUM_OF_INTEGERS;
	private int mMaxDecimalDigit = 2;  //小数位数
	private float mMultipleSteps = 5; //最大调整数
	private double mMinStep = 0.01f; //最小调整数
	private double mMax = Double.MAX_VALUE;
	private double mMin = Double.MIN_VALUE;
	protected OnTextChangedListener mOnTextChangedListener = null;
	private String suffixStr = "";
	private String mDefalutValue = "";

	public NumberInput(Context context) {
		super(context);
		init();
	}

	public NumberInput(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public NumberInput(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();

	}

	/**
	 * 设置输入框内输入数字的范围
	 * @param beforeDot
	 * @param afterDot
	 */
	public void setDigits(int maxlength,int beforeDot, int afterDot) {
		mMaxDigitBeforeDot = beforeDot;
		mMaxDecimalDigit = afterDot;
		this.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxlength), new DecimalDigitsInputFilter(beforeDot, afterDot) });
	}
	
	/**
	 * 设置后缀值
	 * @param str
	 */
	public void setSuffixStr(String str){
		suffixStr = str;
	}
	
	/**
	 * 设置默认值
	 * @param value
	 */
	public void setDefalutValue(String value){
		mDefalutValue = value;
	}

	/**
	 * 
	 * @param decimalPoint
	 */
	public void setDecimalDigits(int decimalPoint) {
		setDigits(MAX_NUM_OF_INTEGERS, MAX_NUM_OF_INTEGERS, decimalPoint);
	}

	public void setMin(double min) {
		mMin = min;
	}

	public void setMax(double max) {
		mMax = max;
	}

	public void setMinSteps(double step) {
		mMinStep = step;
	}

	public void setMultipleSteps(int multiple) {
		mMultipleSteps = multiple;
	}

	/**
	 * doule类型转换成string类型
	 * @param value
	 * @return
	 */
	public String valueToString(double value) {
		ProductPrecision precision = new ProductPrecision(mMaxDecimalDigit);
//		Logger.e("valueToString = " + value + ", " + precision.format(value));
		return precision.format(value);
	}

	/**
	 * 返回double类型数值
	 * @return
	 */
	public double getValue() {
		String value = getValueString();
		return DoubleConverter.toDoubleData(value);
	}
	
	/**
	 * 返回点数值
	 * @return
	 */
	public int getIntValue() {
		String value = getValueString();
		return DoubleConverter.toIntData(value);
	}
	
	/**
	 * 返回float点数值
	 * @return
	 */
	public Float getFloatValue() {
		String value = getValueString();
		return Float.valueOf(value);
	}

	/**
	 * 返回str类型数据
	 * @return
     */
	public String getStrValue(){
		String str = getText().toString();
		return str;
	}
	
	public String getValueString() {
		//处理整数时后面加“点”的情况
		String value = getText().toString();
		if(value.length() > 0 && !value.equals(".")){
			if(value.contains(getContext().getResources().getString(R.string.order_title_suff))){
				value = value.substring(0, value.length()-1);
			}
		}else{
			value = "0";
		}
		return value;
	}
	
	/**
	 * 止损止盈选项输入框值处理
	 * @return
	 */
	public String getTextValue() {
		//处理整数时后面加“点”的情况
		String value = getText().toString();
		if(value.contains(getContext().getResources().getString(R.string.order_title_suff))){
			value = value.substring(0, value.length()-1);
		}
		return value;
	}

	/**
	 * 止损止盈选项，判断输入框是否输入空值
	 * @return
	 */
	public boolean isEmpty(){
		String value = getText().toString();
		if(value.equals("")){
			return true;			
		}else{
			return false;
		}
	}
	
	/**
	 * 止损止盈选项，判断输入框是否输入空值或者0
	 * @return
	 */
	public boolean isEmptyOrZero(int digit){
		String value = getText().toString();
		if(value.length() > 0 && !value.equals(".")){
			if(DoubleConverter.isEqual(DoubleConverter.toFloatData(getTextValue()), 0, digit)){
				return true;
			}else{
				return false;
			}
		}
		return true;
	}

	/**
	 * 判断是否为0，0返回true，否则返回false
	 * @return
	 */
	private boolean checkzero() {
		final Double beforeValue = getValue();
		if (beforeValue == 0.0 ) {
			return true;
		}
		return false;
	}

	/**
	 * 检查价格范围值
	 * @param value
	 * @return
	 */
	private double checkRange(double value) {
		if (value > mMax)
			value = mMax;
		else if (value < mMin)
			value = mMin;

		return value;
	}

	public void setAfterTextChangedListener(OnTextChangedListener l) {
		mOnTextChangedListener = l;
	}

	/**
	 * 按最小幅度增加价格值
	 */
	public void incMinSteps() {
		if (checkzero()){
			if(mMin == Double.MIN_VALUE){
				setTextValue(mDefalutValue);
				Logger.e("mDefalutValue = " + mDefalutValue);
				return;
			}else{
				if(!DoubleConverter.isEqual(mMin, 0, 2)){
					setTextValue(valueToString(mMin));
					return;
				}
			}
		}

		Double curValue = getValue();
		curValue += mMinStep;
		curValue = checkRange(curValue);
		setTextValue(valueToString(curValue));
	}
	/**
	 * 按最小幅度减少价格值
	 */
	public void decMinSteps() {
		if (checkzero()){
			if(mMin == Double.MIN_VALUE){
				setTextValue(mDefalutValue);
			}else{
				setTextValue(valueToString(mMin));
			}
			return;
		}

		Double curValue = getValue();
		curValue -= mMinStep;
		curValue = checkRange(curValue);
		setTextValue(valueToString(curValue));
	}

	/**
	 * 按最大幅度增加价格值
	 */
	public void incMultipleSteps() {
		Double curValue = getValue();
		curValue += (mMinStep * mMultipleSteps);
		curValue = checkRange(curValue);
		setTextValue(valueToString(curValue));
	}
	/**
	 * 按最大幅度减少价格值
	 */
	public void decMultipleSteps() {
		if (checkzero()){
			setTextValue(valueToString(mMin));
			return;
		}

		Double curValue = getValue();
		curValue -= (mMinStep * mMultipleSteps);
		curValue = checkRange(curValue);
		setTextValue(valueToString(curValue));
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	void init() {
		setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
		setTextValue("");
		setDigits(MAX_NUM_OF_INTEGERS, mMaxDigitBeforeDot, mMaxDecimalDigit);
		setGravity(Gravity.CENTER);
		setCursorVisible(true);
		setImeOptions(EditorInfo.IME_FLAG_NO_FULLSCREEN | EditorInfo.IME_ACTION_NONE);

		// if text changes, take care of the button
		this.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void afterTextChanged(Editable arg0) {
				if (mOnTextChangedListener != null)
					mOnTextChangedListener.onTextChanged(NumberInput.this, arg0);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
		});
	}

	/**
	 * 设置控件不可操作
	 */
	public void disabledWithText(String text) {
		setEnabled(false);
		setTextValue(text);
	}
	
	/**
	 * 设置值
	 */
	public void setTextValue(String text) {
		setText(text + suffixStr);
	}

	/**
	 * 
	 */
	public void setEnabled(boolean enabled, boolean disableBackground) {
		if (enabled) {
			setDigits(MAX_NUM_OF_INTEGERS,mMaxDigitBeforeDot, mMaxDecimalDigit);
		} else {
			if (disableBackground) {
				setBackgroundColor(Color.TRANSPARENT);
				setGravity(Gravity.CENTER);
			}
		}

		super.setEnabled(enabled);
	}

	@Override
	public void setEnabled(boolean enabled) {
		setEnabled(enabled, true);
	}

	/**
	 * 价格过滤器，使用正则表达式确定输入格式
	 * @author Administrator
	 *
	 */
	public final class DecimalDigitsInputFilter implements InputFilter {

		Pattern mPattern;

		/**
		 * @param digitsBeforeZero 整数位数
		 * @param digitsAfterZero 小数位数
		 */
		public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
			//处理整数时后面加“点”的情况
			if(0 == digitsAfterZero){
				mPattern = Pattern.compile("[0-9]{0," + digitsBeforeZero +"}");
			}else{
				mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero)
						+ "}+((\\.[0-9]{0," + (digitsAfterZero) + "})?)||(\\.)?");
			}
		}

		@Override
		public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

			String ret = dest.subSequence(0, dstart).toString() + source.toString() + dest.subSequence(dend, dest.length());
			Matcher matcher = mPattern.matcher(ret);
			if (!matcher.matches())
				return "";
			return null;
		}

	}
}
